{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def epsilon_greedy(nA, R, T, epsilon=0.6):\n",
    "    \"\"\"\n",
    "    输入：\n",
    "       nA 动作数量\n",
    "       R 奖励函数\n",
    "       T 迭代次数\n",
    "    \"\"\"\n",
    "    # 初始化累积奖励 r\n",
    "    r = 0          \n",
    "    count = [0]*nA\n",
    "    \n",
    "    for _ in range(T):\n",
    "        if np.random.rand() < epsilon:\n",
    "            # 探索：以均匀分布随机选择\n",
    "            a = np.random.randint(q_value.shape[0])\n",
    "        else:\n",
    "            # 利用：选择价值函数最大的动作\n",
    "            a = np.argmax(q_value[:])\n",
    "        \n",
    "        # 更新累积奖励和价值函数\n",
    "        v = R(a)\n",
    "        r = r + v\n",
    "        q_value[a] = (q_value[a] * count[a] + v)/(count[a]+1)\n",
    "        count[a] += 1\n",
    "        \n",
    "    return r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
